package org.btik.light.mobile.common.handler.nbi;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;
import org.btik.light.mobile.R;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 单线程
 *
 * @author lustre
 * @since 2023/5/1 22:05
 */
public class NbiAgent {

    private DatagramSocket serverSocket;

    private DatagramPacket datagramPacket;

    private static final NbiAgent INSTANCE = new NbiAgent();

    private final NbiAgentThread nbiAgentThread;

    private String nbiHost;

    private NbiAgent() {
        nbiAgentThread = new NbiAgentThread();
        nbiAgentThread.setName("NbiAgentThread");


    }

    public static void init() throws SocketException {
        INSTANCE.serverSocket = new DatagramSocket();
        INSTANCE.datagramPacket = new DatagramPacket(new byte[0], 0);
        // nbi port
        INSTANCE.datagramPacket.setPort(8008);
        INSTANCE.nbiAgentThread.start();
    }

    public static void setAddress(String nbiHost, Context context) {
        INSTANCE.nbiHost = nbiHost;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            new Thread(() -> doSetAddress(nbiHost, context)).start();
        } else {
            doSetAddress(nbiHost, context);
        }


    }

    private static void doSetAddress(String nbiHost, Context context) {
        InetAddress address;
        try {
            address = InetAddress.getByName(nbiHost);
        } catch (UnknownHostException e) {
            CharSequence cannotResolveHost = context.getText(R.string.can_resolve_server_host);
            Toast.makeText(context, cannotResolveHost + nbiHost, Toast.LENGTH_SHORT).show();
            return;
        }
        INSTANCE.datagramPacket.setAddress(address);
    }


    static void send(RawNbiCommand rawNbiCommand) {
        INSTANCE.nbiAgentThread.rawNbiCommands.add(rawNbiCommand);
    }

    public static String getNbiHost() {
        return INSTANCE.nbiHost;
    }

    static class NbiAgentThread extends Thread {

        ArrayBlockingQueue<RawNbiCommand> rawNbiCommands = new ArrayBlockingQueue<>(32);

        @Override
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    RawNbiCommand take = rawNbiCommands.take();
                    INSTANCE.datagramPacket.setData(take.encode());
                    INSTANCE.serverSocket.send(INSTANCE.datagramPacket);
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
